package com.atom.module.mvvm.extren

import android.widget.CompoundButton
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun CompoundButton.checkedChanges()= callbackFlow<Boolean>  {
    checkMainThread()
    val listener = CompoundButton.OnCheckedChangeListener { _, isChecked ->
        trySend(isChecked)
    }
    setOnCheckedChangeListener(listener)
    awaitClose { setOnCheckedChangeListener(null) }
}
    .conflate()
    .asInitialValueFlow { isChecked }